package com.muyan.netty.aiosocket;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.ExecutionException;

/**
 * 服务端连接处理业务
 * @author zzl
 */
public class ServerAcceptHandler implements CompletionHandler<AsynchronousSocketChannel, Object> {

    private AsynchronousServerSocketChannel socketChannel;

    public ServerAcceptHandler(AsynchronousServerSocketChannel socketChannel) {
        this.socketChannel = socketChannel;
    }

    /**
     * AsynchronousSocketChannel 可以接收
     * @param result
     * @param attachment
     */
    @Override
    public void completed(final AsynchronousSocketChannel result, final Object attachment) {
        // 继续监听下一个连接请求
        socketChannel.accept(attachment, this);
        try {
            System.out.println("接受了一个连接：" + result.getRemoteAddress().toString());
            // 给客户端发送数据并等待发送完成
            result.write(ByteBuffer.wrap("From Server:Hello i am server".getBytes())).get();
            ByteBuffer readBuffer = ByteBuffer.allocate(128);
            // 阻塞等待客户端接收数据
            result.read(readBuffer).get();
            System.out.println(new String(readBuffer.array()));
        } catch (IOException | InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void failed(final Throwable exc, final Object attachment) {
        System.out.println("出错了：" + exc.getMessage());
    }
}
